package com.ecnu.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.bean.BeanUtils;
import com.ecnu.system.domain.SysCommon;
import com.ecnu.system.domain.dto.MessageUpdateDTO;
import com.ecnu.system.domain.dto.ProjectListDTO;
import com.ecnu.system.domain.vo.ActivityVo;
import com.ecnu.system.domain.vo.ProjectListVO;
import com.ecnu.system.mapper.ProjectMapper;
import com.ecnu.system.service.ISysCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ecnu.common.enums.CommonType.*;

@Api(tags = "首页消息框管理")
@RestController
@RequestMapping("/system/message")
public class SysMessageController extends BaseController {
    @Autowired
    private ISysCommonService commonService;
    @Autowired
    private ProjectMapper projectMapper;

//    @ApiOperation(value = "新增首页消息框")
//    @PostMapping("/add")
//    public AjaxResult addMessage(@RequestBody MessageAddDTO messageAddDTO) {
//        SysCommon bottom = new SysCommon();
//        bottom.setCreateBy(getUsername());
//        bottom.setType(HOME_MESSAGE.getCode());
//        BeanUtils.copyProperties(messageAddDTO, bottom);
//        boolean save = commonService.save(bottom);
//        if (!save) {
//            return error("新增失败");
//        }
//        return success("新增成功");
//    }

    @ApiOperation(value = "修改底部信息栏或者首页消息框")
    @PostMapping("/update")
    public AjaxResult updateBottom(@RequestBody MessageUpdateDTO messageUpdateDTO) {
        SysCommon bottom = new SysCommon();
        if (StringUtils.isBlank(messageUpdateDTO.getTitle())) {
            bottom.setTitle("");
        } else {
            bottom.setTitle(messageUpdateDTO.getTitle());
        }
        bottom.setId(messageUpdateDTO.getId());
        bottom.setUpdateBy(getUsername());
        bottom.setStatus(1);
        boolean update = commonService.updateById(bottom);
        if (!update) {
            return error("修改失败");
        }
        return success("修改成功");
    }

    @ApiOperation("查询首页消息框 分页")
    @GetMapping("list")
    public AjaxResult message(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "10") int size) {

        Page<SysCommon> activityPage = new Page<>(page, size);
        Page<SysCommon> paged = commonService.page(activityPage, new QueryWrapper<SysCommon>()
                .eq("type", HOME_MESSAGE.getCode())
                .orderByAsc("sort"));
        // 将查询结果转换为ActivityVo列表
        List<ActivityVo> activityVoList = paged.getRecords().stream().map(sysCommon -> {
            ActivityVo activityVo = new ActivityVo();
            BeanUtils.copyProperties(sysCommon, activityVo);
            activityVo.setId(sysCommon.getId().toString());
            return activityVo;
        }).collect(Collectors.toList());
        // 创建新的分页对象并返回
        Page<ActivityVo> resultPage = new Page<>(paged.getCurrent(), paged.getSize(), paged.getTotal());
        resultPage.setRecords(activityVoList);
        return success(resultPage);
    }


    @ApiOperation(value = "首页消息框（不分页）")
    @GetMapping("/front")
    public AjaxResult listActivitiesFront() {
        List<SysCommon> list = commonService.list(new LambdaQueryWrapper<SysCommon>()
                .eq(SysCommon::getStatus, 1)
                .eq(SysCommon::getType, HOME_MESSAGE.getCode())
                .orderByAsc(SysCommon::getSort));

        if (StringUtils.isBlank(list.get(0).getTitle())) {
            list.clear();
            List<ProjectListVO> projectListVOS = projectMapper.selectListByType(new ProjectListDTO(), new LoginUser(),  null);
            Date date = new Date();
            final Integer[] count = {0};
            projectListVOS.forEach(projectListVO -> {
                if (date.after(projectListVO.getStartTime()) && date.before(projectListVO.getEndTime())) {
                    count[0]++;
                }
            });
            SysCommon sysCommon = new SysCommon();
            sysCommon.setTitle("当前正在进行" + count[0] + "个活动");
            sysCommon.setId(999L);
            list.add(sysCommon);
        }
        List<ActivityVo> activityVoList = list.stream().map(sysCommon -> {
            ActivityVo activityVo = new ActivityVo();
            BeanUtils.copyProperties(sysCommon, activityVo);
            activityVo.setId(sysCommon.getId().toString());
            return activityVo;
        }).collect(Collectors.toList());
        return success(activityVoList);
    }

    @ApiOperation(value = "删除数据")
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteBanner(@PathVariable Long id) {
        boolean remove = commonService.removeById(id);
        if (!remove) {
            return error("删除失败");
        }
        return success("删除成功");
    }
}
